//
//  FunctionTableViewController.m
//  OpenYourEyes
//
//  Created by apple on 15/8/14.
//  Copyright (c) 2015年 zhanglei. All rights reserved.
//

#import "FunctionTableViewController.h"
#import "FlowTableViewCell.h"

@interface FunctionTableViewController ()<UIAlertViewDelegate>

@property (nonatomic ,strong) NSArray *dataSource;

@property (nonatomic ,assign) float siziCache;

@end

@implementation FunctionTableViewController

- (NSArray *)dataSource
{
    if (_dataSource == nil)
    {
        self.dataSource = [NSArray array];
    }
    return _dataSource;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"功能开关";
    [self sizeCecha];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 1;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        FlowTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"flow"];
        if (cell == nil)
        {
            cell = [[FlowTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"flow"];
            cell.labelFlow.text = @"推送提示";
            cell.switchBlock = ^{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"推送已打开" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
                
                [alert show];
            };
        }
        return cell;
    }
    else if (indexPath.section == 1)
    {
        FlowTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"flow1"];
        if (cell == nil)
        {
            cell = [[FlowTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"flow1"];
            cell.labelFlow.text = @"流量提醒";
            cell.switchBlock= ^{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"流量提醒已打开" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
                [alert show];
            };
            
            return cell;
        }
        return cell;
    }
    else
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
            
        }
        cell.textLabel.text = @"清除缓存";

        cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2fM",_siziCache];
                
        return cell;
    }
}
//点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2)
    {
        if([self folderSizeAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/default"]] == 0)
        {
            [self cachesIsNull];
        }
        else{
            [self clearCaches];
            
        }
        [self.tableView reloadData];
        
    }
}
#pragma mark - 清除缓存
- (void)cachesIsNull
{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"暂无缓存" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil] ;
    [alert show];
    [self performSelector:@selector(missAlertView:) withObject:alert afterDelay:1.0];
}

- (void)sizeCecha
{
    NSString * filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/default"];
    float result = [self folderSizeAtPath:filePath];
    _siziCache = result;
}

//清除缓存
- (void)clearCaches
{
    
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"缓存大小为%.2fM.确定要清理缓存吗?",_siziCache] delegate:self cancelButtonTitle:@"确认" otherButtonTitles:@"取消",nil];
        [alertView show ];
    
}

//代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if(buttonIndex == 0 && ![alertView.message isEqualToString:@"推送已打开"] && ![alertView.message isEqualToString:@"流量提醒已打开"])
    {
        NSFileManager * manger = [NSFileManager defaultManager];

        NSString *string = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/default"];
        [manger removeItemAtPath:string error:nil];

        [self.tableView reloadData];
        
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"清除缓存成功" delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
        [alert show];
        [self performSelector:@selector(missAlertView:) withObject:alert afterDelay:1.0];
        [self sizeCecha];
    }
}

- (void)missAlertView:(UIAlertView *)alert
{
    [alert dismissWithClickedButtonIndex:0 animated:YES];
}

- (long long)fileSizeAtPath:(NSString *)filePath
{
    NSFileManager * manager = [NSFileManager defaultManager];
    
    if([manager fileExistsAtPath:filePath])
    {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0 ;
}

//计算沙盒的缓存
- (float)folderSizeAtPath:(NSString *)folderPath
{
    NSFileManager * manager = [NSFileManager defaultManager];
    //如果文件不存在，就返回0
    if (![manager fileExistsAtPath :folderPath])
    {
        return 0 ;
    }
    //NSEnumerator类似于NSArray，一般不单独使用。只是作为 NSArray，NSSet 和 NSDictionary 的辅助类
    //NSEnumerator 中的元素一旦遍历过之后就不能重新遍历，必须重新创建一个NSEnumerator。
    NSEnumerator * childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString * fileName = [childFilesEnumerator nextObject];
    long long folderSize = 0 ;
    while((fileName = [childFilesEnumerator nextObject]) != nil)
    {
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [ self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/ (1024.0  * 1024.0);
}

@end
